<!-- 图片上传组件 
用法示列
<imgUpload
              :acceptSize="2 * 1024 * 1024"
              :auto-upload="false"
              :imgFileList="user.photoUrl"
              :show-file-list="true"
              dir="userHeadImg"
              :limit="1"
              @setUrl="setUrl"
              list-type="picture-card"
              ref="imgFileRef"
            >
            </imgUpload>
  当模态框显示后，需要显示调用init()方法，示列如下：
  this.dialogDetailBox=true;
  this.$nextTick(() => {
    this.$refs.imgFileRef.init();
  });
-->
<template>
  <div>
    <el-upload
      :accept="accept"
      :action="action"
      :auto-upload="autoUpload"
      :before-upload="beforeUpload"
      :data="fileOtherData"
      :file-list="fileList"
      :limit="limit"
      :multiple="multiple"
      :on-change="handleChange"
      :on-error="handleError"
      :on-success="handleSuccess"
      :on-exceed="handleExceed"
      :on-remove="handleRemove"
      :ref="imgUploadRef"
      :show-file-list="showFileList"
      class="avatar-uploader"
      list-type="picture-card"
    >
      <i slot="default" class="el-icon-plus"></i>
    </el-upload>
    <el-button
      style="margin-left: 10px;"
      size="small"
      type="success"
      @click.stop="submitUpload"
    >上传到服务器</el-button>
  </div>
</template>

<script>
import { get } from "@/utils/request.js";

export default {
  props: {
    imgUploadRef: {
      type: String,
      default: "file1"
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: true
    },
    // 是否自动上传
    autoUpload: {
      type: Boolean,
      default: false
    },
    // 是否显示上传列表
    showFileList: {
      type: Boolean,
      default: true
    },
    // 最大允许上传个数
    limit: {
      type: Number,
      default: null
    },
    // 允许上传的文件类型
    accept: {
      type: String,
      default: "image/jpeg, image/gif, image/png, image/bmp"
    },
    // 允许上传的文件大小 单位：字节
    acceptSize: {
      type: Number,
      default: null
    },
    // 默认额外上传数据
    fileOtherData: {
      type: Object,
      default: function() {
        return {
          key: "",
          policy: "",
          OSSAccessKeyId: "",
          success_action_status: 200,
          signature: ""
        };
      }
    },
    // 文件存储目录
    dir: "",
    // 图片数组
    imgFileList: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: true,
      // 是否上传失败
      isUploadError: false,
      fileLength: 0,
      action: "",
      waitUpload: [],
      fileList: []
    };
  },
  // watch: {
  //   imgFileList: function(val) {
  //     this.successFileList = this.successFileList.filter(function(item) {
  //       var isexist = false;
  //       for (var i = 0; i < val.length; i++) {
  //         if (val[i].name == item.name) {
  //           isexist = true;
  //         }
  //       }
  //       return isexist;
  //     });
  //   }
  // },
  computed: {},
  methods: {
    init() {
      this.fileList = [...this.imgFileList];
    },
    // 附件上传前触发
    async beforeUpload(file) {
      const vm = this;
      const isLtAcceptSize = file.size > vm.acceptSize;
      if (isLtAcceptSize) {
        setTimeout(() => {
          vm.$message.error(
            "只能上传" +
              vm.renderSize(vm.acceptSize) +
              "的文件!已为您过滤文件：" +
              file.name
          );
        }, 10);
        return false;
      } else {
        vm.isUploadError = false;
      }
      await get("/file/getPolicyUploadInfo", { dir: vm.dir }).then(res => {
        vm.fileOtherData.key = vm.dir + "/" + new Date().getTime() + file.name;
        vm.fileOtherData.policy = res.data.data.policy;
        vm.fileOtherData.OSSAccessKeyId = res.data.data.accessid;
        vm.fileOtherData.signature = res.data.data.signature;
        vm.action = res.data.data.host;
      });
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleChange(file, fileList) {
      const vm = this;
      console.log(file);
      if (file.status == "ready") {
        vm.waitUpload.push({ uid: file.uid });
      }
      if ("success" === file.status) {
        // vm.imgFileList
        // let exist=false;
        // for(let i=0;i<vm.imgFileList.length;i++) {
        //   if(vm.imgFileList[i].url === )
        // }
        // vm.imgFileList.push({name:file.name,url:vm.action+"/"+vm.fileOtherData.key});
        console.log("handleChange success", vm.imgFileList);
        console.log("handleChange success", fileList);
      }
    },
    renderSize(value) {
      if (null == value || value == "") {
        return "0 B";
      }
      const unitArr = new Array(
        "B",
        "KB",
        "MB",
        "GB",
        "TB",
        "PB",
        "EB",
        "ZB",
        "YB"
      );
      let index = 0;
      let srcsize = parseFloat(value);
      index = Math.floor(Math.log(srcsize) / Math.log(1024));
      let size = srcsize / Math.pow(1024, index);
      size = size.toFixed(2);
      if (unitArr[index]) {
        return size + unitArr[index];
      }
      return "文件太大";
    },
    handleSuccess(response, file, fileList) {
      let vm = this;
      vm.imgFileList.push({
        name: file.name,
        url: vm.action + "/" + vm.fileOtherData.key
      });
      vm.waitUpload.forEach((item, index) => {
        if (item.uid === file.uid) {
          vm.waitUpload.splice(index, 1);
        }
      });
      vm.$message.success("上传成功");
      vm.$emit("setUrl", vm.action + "/" + vm.fileOtherData.key);
    },
    // 附件上传失败
    handleError() {
      const vm = this;
      vm.$message.error("上传失败，请重试");
      vm.isUploadError = true;
    },
    // 删除附件回调
    handleRemove(file, fileList) {
      const vm = this;
      vm.imgFileList.forEach((item, index) => {
        if (item.name === file.name) {
          vm.imgFileList.splice(index, 1);
        }
      });
      vm.waitUpload.forEach((item, index) => {
        if (file.uid && item.uid === file.uid) {
          vm.waitUpload.splice(index, 1);
        }
      });
      vm.$emit("removeUrl", file.name);
      return true;
    },
    // 文件超出个数限制时的钩子
    handleExceed() {
      const vm = this;
      vm.$message("当前最多允许上传" + vm.limit + "张图片");
    },
    // 附件上传服务器触发方法
    async submitUpload() {
      const vm = this;
      if (vm.waitUpload.length < 1) {
        vm.$message("请先选择图片！");
        return;
      }
      await vm.$refs[vm.imgUploadRef].submit();
    }
  }
};
</script>
<style scoped>
.avatar {
  width: 100%;
  height: 100%;
}
.el-form-item__content {
  line-height: 0;
}
.el-upload-list--picture-card .el-upload-list__item {
  margin: 0 8px 0 0;
}
.el-upload--picture-card,
.el-upload-list--picture-card .el-upload-list__item {
  width: 128px;
  height: 128px;
}
.limit .el-upload--picture-card {
  display: none;
}
</style>
